﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using Orion.Models;
using Orion.MyLib;


namespace Orion.Controllers
{
	[HandleError]
    public class EventController : Controller
    {
        private EventRepository m_eventRep = new EventRepository();
        private HomeIndexViewModel m_viewModel = new HomeIndexViewModel();
        private int displayNewsArticles = 100;

        public ActionResult Index( )
        {
        	try
        	{
				//active events and visible for everyone fetched
				var temp = m_eventRep.GetAllEvents( );
				m_viewModel.Events = from t in temp
									 where t.UserGroup == "Allir"
									 select t;

				m_viewModel.counter = m_viewModel.Events.Count();

				//nr of events per page set.
				m_viewModel.displayNewsArticle = displayNewsArticles;

				//nr of pages calculated
				var n = m_viewModel.counter;
				m_viewModel.counter = n / displayNewsArticles;
				if( n % displayNewsArticles != 0 )
				{
					m_viewModel.counter++;
				}

				return View(m_viewModel);
        	}
        	catch ( Exception ex )
        	{
        		var log = new Logger( );
				log.LogExcepion( ex );
        		return View( "Error" );
        	}
        }

        [Authorize(Roles = "Staff, Admin")]
        public ActionResult ClosedEvent( )
        {
        	try
        	{
				//active events and only visible for staff fetched
				var temp = m_eventRep.GetAllEvents( );
				m_viewModel.Events = from t in temp
									 where t.UserGroup == "Lokaður"
									 select t;

				m_viewModel.counter = m_viewModel.Events.Count( );

				//nr of events per page set.
				m_viewModel.displayNewsArticle = displayNewsArticles;

				//nr of pages calculated
				var n = m_viewModel.counter;
				m_viewModel.counter = n / displayNewsArticles;
				if (n % displayNewsArticles != 0 )
				{
					m_viewModel.counter++;
				}

				return View( m_viewModel );
        	}
        	catch (Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex) ;
				return View( "Error" );
        	}
			
        }

		public ActionResult EventById( int? id )
		{
			//validation
			if (! id.HasValue )
			{
				return RedirectToAction( "Index" );
			}
	
			var model = m_eventRep.GetEventById( id.Value );

			return View( model );
		}

		[Authorize(Roles = "Staff, Admin")]
		public ActionResult Create( )
		{
			return View( new Event( ) );
		}

		[Authorize(Roles = "Staff, Admin")]
		[HttpPost]
		public ActionResult Create( Event ev, HttpPostedFileBase file )
		{
			try
			{
				//validation
				if (!ModelState.IsValid)
				{
					return View( ev );
				}
				//check if file was included
				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/EventMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/EventMyndir"), ev.Title.Trim() + "." + fileEnding[1]);

					//validate folder exist
					if ( ! Directory.Exists(folder ) )
					{
						Directory.CreateDirectory( folder );
					}

					file.SaveAs( path );
					ev.Picture = string.Format("/Content/EventMyndir/{0}.{1}", ev.Title.Trim(), fileEnding[1] );
				}

				ev.Author = User.Identity.Name;
				m_eventRep.AddEvent( ev );

				return RedirectToAction("Index");
			}
			catch ( Exception ex )
			{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
			}
		}


		[Authorize(Roles = "Staff, Admin") ]
		public ActionResult Edit( int? id )
		{
			//validation
			if ( ! id.HasValue )
			{
				return RedirectToAction( "Index" );
			}

			var model = m_eventRep.GetEventById( id.Value );

			return View( model );
		}

		[Authorize(Roles = "Staff, Admin")]
		[HttpPost]
		public ActionResult Edit(FormCollection form, HttpPostedFileBase file)
		{
			try
			{
				//validation
				if ( ! ModelState.IsValid )
				{
					return View( form );
				}

				var ev = new Event( );
				UpdateModel( ev );

				//ID is returned as string, for some reason need to change it back to int for use.
				int temp;
				if (!int.TryParse(form["ID"], out temp))
				{
					throw new Exception("ID af atburð tapaðist við tilraun til þess að breyta honum");
				}
				ev.ID = temp;

				//check if file was included
				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/EventMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/EventMyndir"), ev.ID + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					ev.Picture = string.Format("/Content/EventMyndir/{0}.{1}", ev.ID, fileEnding[1]);
				}

				m_eventRep.UpdateEvent( ev );

				return RedirectToAction( "Index", "Work" );
			}
			catch ( Exception ex )
			{
				var log = new Logger( );
				log.LogExcepion( ex) ;
				return View( "Error" );
			}
			
		}

		public static IEnumerable<Event> GetAllActiveEvents()
		{
			var eventRep = new EventRepository();

			var model = eventRep.GetAllEvents();

			return model;
		}
    }
}
